﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RBAC.Api.Demain.Entities;
using RBAC.Api.Erroc;
using RBAC.Api.Infaction;
using RBAC.Api.Writh.Command.Roles;
using System.Linq.Dynamic.Core;

namespace RBAC.Api.Writh.CommandHandler.Roles
{
    public class UpdateRoleCommandHandler : IRequestHandler<UpdateRoleCommand, APIResult<object>>
    {
        private readonly IBaseRepositry<Role> role;
        private readonly IBaseRepositry<RolePermission> rolepermission;
        private readonly IMapper mapper;

        public UpdateRoleCommandHandler(IBaseRepositry<Role> baseRepositry,
                            IBaseRepositry<RolePermission> baseRepositry1,
                            IMapper mapper
                            )
        {
            this.role = baseRepositry;
            this.rolepermission = baseRepositry1;
            this.mapper = mapper;
        }
        public async Task<APIResult<object>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result=new APIResult<object>();
            result.Code = ResultCode.Success;
            result.Message = "修改角色成功";


            
            var strategy = role.Context.Database.CreateExecutionStrategy();

            await strategy.ExecuteAsync(async () =>
            {

                using (var tran = await role.Context.Database.BeginTransactionAsync())
                { 
                  
                    try
                    { 
                        var roles=mapper.Map<Role>(request);
                       
                        await role.Update(roles);

                        //删除角色权限
                        var rolepermissions=rolepermission.GetAll().Where(x=>x.RoleId==request.Id).ToList();
                        foreach(var item in rolepermissions)
                        {
                            await rolepermission.Delete(item);
                        }

                        //添加角色权限
                        foreach (var item in request.PermissionId)
                        {
                            RolePermission permission = new()
                            {
                                RoleId=roles.Id,
                                PermissionId=item,
                                CreateTime=DateTime.Now,
                            };
                            await rolepermission.Add(permission);
                        }

                        await tran.CommitAsync();   
                    }
                    catch (Exception ex)
                    {
                        await tran.RollbackAsync();
                    }
                };

            });


            return await Task.FromResult(result);
        }
    }
}
